<template>
  <table-header
    placeholder="请输入媒资名称"
    :queryList="queryList"
    @pagination="getDataList"
    :rightColSpan="4"
    :leftColSpan="20"
  >
    <template #filter>
      <!--<el-autocomplete
                v-model="queryList.keyword"
                :fetch-suggestions="handleSearchSuggest"
                :trigger-on-focus="false"
                class="inline-input"
                autofocus="true"
                :clearable="true"
                @clear="getDataList"
                placeholder="请输入媒资名称"
                @keyup.enter="getDataList"
                @select="getDataList"
                size="small"
            />-->
      <el-select
        v-model="queryList.groupid"
        size="small"
        style="margin-right: 10px"
        placeholder="请选择部门"
        @change="handleGroupChange"
        clearable
        @clear="handleGroupClear"
      >
        <el-option
          v-for="item in groupLists"
          :key="item.groupid"
          :label="item.name"
          :value="item.groupid"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="queryList.mediatype"
        size="small"
        style="margin-right: 10px"
        placeholder="请选择媒资类型"
        @change="handleMediaTypeChange"
        clearable
        @clear="handleMediaTypeClear"
      >
        <el-option
          v-for="(item, index) in mediaTypes"
          :key="index"
          :label="item"
          :value="index"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="queryList.catid"
        size="small"
        style="margin-right: 10px"
        placeholder="请选一级分类"
        @change="handleCategoryChange"
        clearable
        @clear="handleCategoryClear"
      >
        <el-option
          v-for="item in categoryData"
          :key="item.catid"
          :label="item.name"
          :value="item.catid"
        >
        </el-option>
      </el-select>
      <el-input
        placeholder="请输入媒资名称"
        v-model="queryList.keyword"
        style="width: 200px"
        :clearable="true"
        @clear="handleKeywordClear"
        size="small"
        @keyup.enter="getDataList"
      />
    </template>
    <template #default>
      <el-button
        size="small"
        type="primary"
        style="margin-left: 10px"
        @click="getDataList"
      >
        搜索
      </el-button>
      <!--<el-button
                size="small"
                type="primary"
                @click="handleDialog('AndvancedSearch')"
            >
                高级搜索
            </el-button>-->
    </template>
    <template #operation>
      <el-dropdown @command="handleBatchCommand" style="margin-right: 10px">
        <el-button size="small" type="primary">
          批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="review">批量申请审核</el-dropdown-item>
            <el-dropdown-item command="online">批量上线</el-dropdown-item>
            <el-dropdown-item command="offline">批量下线</el-dropdown-item>
            <el-dropdown-item command="refpackage"
              >批量加内容包</el-dropdown-item
            >
            <el-dropdown-item command="mediashare">批量分享</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <!--<el-button type="primary" size="small" @click="handleDialog('OriginalLibrary')">
                媒资素材库
            </el-button>-->
      <el-button type="primary" size="small" @click="handleCreate">
        <el-icon>
          <plus />
        </el-icon>
        新建
      </el-button>
    </template>
  </table-header>
  <el-table
    class="mt10 mb10"
    v-loading="isloading"
    :data="tableData.listData"
    border
    :height="tableHeight"
    @selection-change="handleSelectionChange"
    @row-click="
      (row) => {
        handleRowClick(row);
      }
    "
    @sort-change="handleTableSortChange"
    ref="tableref"
  >
    <el-table-column type="selection" width="40" align="center" />
    <el-table-column label="缩略图" width="60">
      <template #default="{ row }">
        <div @click.stop>
          <el-image
            v-if="row.thumbs.length > 0 && typeof row.thumbs[0] == 'object'"
            :preview-src-list="srcList"
            :initial-index="srcList.indexOf(row.thumbs[0].viewurl)"
            :src="
              row.thumbs[0].isself == 1 &&
              row.thumbs[0].sourcefrom == 'cloudstorage'
                ? row.thumbs[0].viewurl + '&width=50'
                : row.thumbs[0].viewurl
            "
          />
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="媒资ID"
      prop="mediaid"
      width="80px"
      align="center"
    />
    <el-table-column
      label="媒资名称"
      width="150px"
      :show-overflow-tooltip="true"
    >
      <template #default="{ row }">
        <a
          v-if="row.highlight && row.highlight.name"
          v-html="row.highlight.name"
          href="javascript:;"
          @click.stop="handleMediaDetail(row)"
        ></a>
        <a href="javascript:;" @click.stop="handleMediaDetail(row)" v-else>{{
          row.name
        }}</a>
      </template>
    </el-table-column>
    <el-table-column
      label="媒资类型"
      width="70px"
      :show-overflow-tooltip="true"
      align="center"
    >
      <template #default="{ row }">
        {{ row.mediatypename }}
      </template>
    </el-table-column>
    <el-table-column
      label="媒资分类"
      width="70px"
      :show-overflow-tooltip="true"
      align="center"
    >
      <template #default="{ row }">
        <p class="txttdellipsis">{{ row.catname }}</p>
      </template>
    </el-table-column>
    <el-table-column label="是否多集" width="70px" align="center">
      <template #default="{ row }">
        <span v-if="row.hasseries == 1">是</span>
        <span v-else>否</span>
      </template>
    </el-table-column>
    <el-table-column
      label="创建时间"
      width="150px"
      align="center"
      prop="cts"
      sortable="custom"
    >
      <el-table-column
        label="更新时间"
        width="150px"
        align="center"
        prop="mts"
        sortable="custom"
      >
        <template #default="{ row }">
          {{ row.ctime.replace("T", " ").replace("Z", "") }}<br />
          {{ row.mtime.replace("T", " ").replace("Z", "") }}
        </template>
      </el-table-column>
    </el-table-column>
    <el-table-column
      label="所属部门"
      width="100px"
      align="center"
      :show-overflow-tooltip="true"
    >
      <template #default="{ row }">
        <span v-if="row.groupname != undefined">{{ row.groupname }}</span>
        <span v-else>-</span>
      </template>
    </el-table-column>
    <el-table-column label="关联内容包" width="100px">
      <template #default="{ row }">
        <template v-if="row.packagenames && row.packagenames.length > 0">
          <!--<p class="txttdellipsis" v-for="packagename in row.packagenames" :key="packagename">{{packagename}}</p>-->
          <el-tooltip placement="right">
            <template #content>
              <template
                v-for="packagename in row.packagenames"
                :key="packagename"
                >{{ packagename }}<br
              /></template>
            </template>
            <span>
              <p
                class="txttdellipsis"
                v-for="packagename in row.packagenames.slice(0, 1)"
                :key="packagename"
              >
                {{ packagename }}
              </p>
            </span>
          </el-tooltip>
        </template>
        <template v-else> - </template>
      </template>
    </el-table-column>
    <!--<el-table-column label="关联商品" v-if="queryList.mediatype == 'liveroom'">
      <template #default="{ row }">
        <p v-if="listGoodsCount[row.mediaid] != undefined">
          {{ listGoodsCount[row.mediaid] }}
        </p>
        <p v-else>-</p>
      </template>
    </el-table-column>-->
    <el-table-column label="审核状态" width="70px" align="center">
      <template #default="{ row }">
        <span v-if="row.state == 0">未提交</span>
        <span v-else-if="row.state == 1">审核中</span>
        <span v-else-if="row.state == 2">审核通过</span>
        <span v-else-if="row.state == 3">审核失败</span>
        <span v-else-if="row.state == 4">免审</span>
        <span v-else>-</span>
      </template>
    </el-table-column>
    <el-table-column label="付费类型" width="70px" align="center">
        <template #default="{row}">
            <span v-if="row.paytype == 0" style="color:#67C23A">免费</span>
            <span v-else-if="row.paytype == 1" style="color:#f56c6c">付费</span>
            <span v-else>-</span>
        </template>
    </el-table-column>
    <el-table-column label="状态" width="60px" align="center">
      <template #default="{ row }">
        <!--只有审核通过和免审时才可操作上下线-->
        <template v-if="row.state == 2 || row.state == 4">
          <el-button
            v-if="row.inuse == 1"
            type="text"
            size="mini"
            @click.stop="handleOnOff(row)"
            >上线</el-button
          >
          <el-button
            v-else
            type="text"
            style="color: #f56c6c"
            size="mini"
            @click.stop="handleOnOff(row)"
            >下线</el-button
          >
        </template>
        <template v-else>
          <el-button
            v-if="row.inuse == 1"
            type="text"
            size="mini"
            :disabled="true"
            >上线</el-button
          >
          <el-button v-else type="text" size="mini" :disabled="true"
            >下线</el-button
          >
        </template>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="180px">
      <template #default="{ row }">
        <el-button
          v-if="canEditMediaType.indexOf(row.mediatype) > -1 && row.state != 1"
          type="text"
          size="mini"
          @click.stop="handleEdit(row)"
        >
          编辑
        </el-button>
        <el-button v-else type="text" size="mini" :disabled="true">
          编辑
        </el-button>
        <el-button
          v-if="row.state == 0 || row.state == 3"
          type="text"
          size="mini"
          @click.stop="handleReview(row)"
          >申请审核</el-button
        >
        <el-button v-else type="text" size="mini" :disabled="true"
          >申请审核</el-button
        >
        <el-button
          v-if="row.isaddseries == 1"
          type="text"
          size="mini"
          @click.stop="handleSeriesList(row)"
          >子集列表</el-button
        >
        <el-button v-else type="text" size="mini" :disabled="true"
          >子集列表</el-button
        >
        <br />
        <el-button
          size="mini"
          type="text"
          @click.stop="handleDialog('MediaShare', row)"
        >
          分享
        </el-button>
        <el-button
          size="mini"
          type="text"
          @click.stop="handleDialog('RelPackage', row)"
          >加内容包</el-button
        >
        <el-button
          v-if="queryList.mediatype == 'liveroom'"
          size="mini"
          type="text"
          @click.stop="handleDialog('LiveRoomReview', row)"
        >
          预览直播间
        </el-button>
        <br v-if="queryList.mediatype == 'liveroom'" />
        <media-delete-button :row="row" @reloadLists="reloadLists"></media-delete-button>
        <media-ciku-button v-if="queryList.mediatype == 'liveroom'" :row="row" />
      </template>
    </el-table-column>
  </el-table>
  <table-pagination
    :queryList="queryList"
    :total="tableData.total"
    @pagination="getDataList"
  />

  <component
    :is="asyncComponentAndvancedSearch"
    :title="dialogTitle"
    :visible="dialogVisible.AndvancedSearch"
    :queryList="queryList"
    @cancelDialog="cancelDialog('AndvancedSearch')"
    @getData="getDataList"
    @handleSearchSuggest="handleSearchSuggest"
  />
  <component
    :is="asyncComponentOriginalLibrary"
    :title="dialogTitle"
    :visible="dialogVisible.OriginalLibrary"
    :groupid="groupid"
    @cancelDialog="cancelDialog('OriginalLibrary')"
  />
  <component
    :is="asyncComponentRelPackage"
    :title="dialogTitle"
    :visible="dialogVisible.RelPackage"
    :toDialogData="toDialogData"
    @getData="getDataList"
    @cancelDialog="cancelDialog('RelPackage')"
    :key="relPackageComponentsKey"
  />
  <component
    :is="asyncComponentMediaShare"
    :title="dialogTitle"
    :visible="dialogVisible.MediaShare"
    :toDialogData="toDialogData"
    @cancelDialog="cancelDialog('MediaShare')"
    @getData="getDataList"
    :key="mediaShareComponentsKey"
  />
  <component
    :is="asyncComponentLiveRoomReview"
    :title="dialogTitle"
    :visible="dialogVisible.LiveRoomReview"
    :toDialogData="toDialogData.medias"
    @cancelDialog="cancelDialog('LiveRoomReview')"
    :key="liveRoomReviewComponentKey"
  />
  <!--<andvanced-search
        :title="'高级搜索'"
        :visible="andvancedSearchVisible"
        :queryList="queryList"
        :mediaTypeKeyValue="mediaTypes"
        @cancelDialog="cancelAndvancedSearchDialog"
        @getData="getDataList"
        @handleSearchSuggest="handleSearchSuggest"
    />-->
</template>

<script>
import { useRoute, useRouter } from "vue-router";
import { ref, reactive, onMounted, defineAsyncComponent } from "vue";
import TableHeader from "@/views/public/TableHeader";
import TableData from "@/views/public/TableData";
import TablePagination from "@/views/public/TablePagination";
import {
  getRelMedias,
  getSearchSuggest,
  mediasOnOff,
  getGroupList
} from "@/api/media/media";
// import getFullHeight from '@/utils/adpative-table.js';
import { useStore } from "vuex";
import { Plus, ArrowDown } from "@element-plus/icons";
import { ElMessage, ElMessageBox } from "element-plus";
import { mediasReview } from "@/api/media/review";
import mediaTypeMixin from "@/mixins/mediaTypeMixin";
import { getCategories } from "@/api/media/constant";
// import { getMediaRelGoods } from "@/api/goods/relgoods";
import MediaDeleteButton from '@/components/Common/Media/DeleteButton'
import MediaCikuButton from '@/components/Common/Media/CikuButton'
export default {
  name: "medialist",
  components: {
    TableHeader,
    TableData,
    TablePagination,
    Plus,
    ArrowDown,
    AndvancedSearch: defineAsyncComponent(() =>
      import("@/views/public/AndvancedSearch")
    ),
    OriginalLibrary: defineAsyncComponent(() =>
      import("../media/components/OriginalLibraryDialog")
    ),
    RelPackage: defineAsyncComponent(() =>
      import("../media/components/RelPackageDialog")
    ),
    MediaShare: defineAsyncComponent(() =>
      import("../media/components/MediaShareDialog")
    ),
    LiveRoomReview: defineAsyncComponent(() =>
      import("../media/components/LiveRoomReview")
    ),
    MediaDeleteButton,
    MediaCikuButton
  },
  setup() {
    const relPackageComponentsKey = ref(Number);
    const mediaShareComponentsKey = ref(Number);
    const liveRoomReviewComponentKey = ref(Number);
    const store = useStore();
    const route = useRoute();
    const router = useRouter();
    const asyncComponentAndvancedSearch = ref(null);
    const asyncComponentOriginalLibrary = ref(null);
    const asyncComponentRelPackage = ref(null);
    const asyncComponentMediaShare = ref(null);
    const asyncComponentLiveRoomReview = ref(null);
    let canEditMediaType = [
      "longvideo",
      "shortvideo",
      "imageset",
      "article",
      "liveroom",
    ];
    // 部门
    const groupLists = ref([]);
    getGroupList().then((response) => {
      groupLists.value = response.data;
    });
    const handleGroupChange = () => {
      getDataList();
    };
    const handleGroupClear = () => {
      router.push({ name: router.currentRoute.value.name });
    };
    // 媒资类型
    const { mediaTypes } = mediaTypeMixin();
    const handleMediaTypeChange = () => {
      if (canEditMediaType.indexOf(queryList.mediatype) >= 0) {
        router.push({
          name: "mediaslist" + queryList.mediatype,
          query: { groupid: queryList.groupid },
        });
      } else {
        router.push({
          name: "mediaslistall",
          query: { groupid: queryList.groupid, mediatype: queryList.mediatype },
        });
        /*if( router.currentRoute.value.name != 'mediaslistall' ){
                        router.push({name:'mediaslistall',query: {groupid : queryList.groupid,mediatype: queryList.mediatype}})
                    }else{
                        queryList.catid=''
                        queryList.page = 1
                        getCategory()
                        getDataList()
                    }*/
      }
    };
    const handleMediaTypeClear = () => {
      router.push({
        name: "mediaslistall",
        query: { groupid: queryList.groupid },
      });
      /*queryList.mediatype = ''
                queryList.catid = ''
                queryList.page = 1
                categoryData.value = []
                getDataList()*/
    };
    // 一级分类
    const categoryData = ref([]);
    const getCategory = () => {
      categoryData.value = [];
      if (queryList.mediatype != "") {
        getCategories({ mediatype: queryList.mediatype, pagesize: 1000 }).then(
          (response) => {
            if (response.errcode == 0) {
              categoryData.value = response.data.list;
            } else {
              console.log(response);
            }
          }
        );
      }
    };
    const handleCategoryChange = () => {
      queryList.page = 1;
      getDataList();
    };
    const handleCategoryClear = () => {
      queryList.catid = "";
      queryList.page = 1;
      getDataList();
    };
    const handleKeywordClear = () => {
      queryList.keyword = "";
      queryList.page = 1;
      getDataList();
    };
    // 图片预览
    const srcList = ref([]);
    // 接收参数
    const groupid =
      route.query.groupid != undefined && route.query.groupid != ""
        ? parseInt(route.query.groupid)
        : "";
    // 搜索条件
    const queryList = reactive({
      page: 1,
      pagesize: 10,
      groupid: groupid,
      corpid: store.getters.corpinfo.corpid,
      keyword: "",
      mediatype: "",
      catid: "",
      orderby: "",
    });
    switch (router.currentRoute.value.name) {
      case "mediaslistliveroom":
        queryList.mediatype = "liveroom";
        break;
      case "mediaslistimageset":
        queryList.mediatype = "imageset";
        break;
      case "mediaslistarticle":
        queryList.mediatype = "article";
        break;
      case "mediaslistshortvideo":
        queryList.mediatype = "shortvideo";
        break;
      case "mediaslistlongvideo":
        queryList.mediatype = "longvideo";
        break;
    }
    if (
      queryList.mediatype == "" &&
      route.query.mediatype != undefined &&
      route.query.mediatype != ""
    ) {
      queryList.mediatype = route.query.mediatype;
    }
    getCategory();
    // 列表相关
    const isloading = ref(true);
    const tableData = reactive({
      total: 0,
      listData: [],
    });
    const listGoodsCount = ref({});
    const getDataList = () => {
      isloading.value = true;
      //queryList.state=1
      getRelMedias(queryList).then((response) => {
        isloading.value = false;
        const { total, list } = response.data;
        tableData.total = total;
        tableData.listData = list;
        srcList.value = [];
        list.forEach((item) => {
          if (typeof item.thumbs[0] == "object") {
            srcList.value.push(item.thumbs[0].viewurl);
          }
          /*if (queryList.mediatype == "liveroom") {
            listGoodsCount.value[item.mediaid] = "加载...";
            getMediaRelGoods({ mediaid: item.mediaid }).then((response) => {
              if (
                response.errcode == 0 &&
                response.data != undefined &&
                response.data.length != undefined
              ) {
                listGoodsCount.value[item.mediaid] = response.data.length;
              } else {
                listGoodsCount.value[item.mediaid] = 0;
              }
            });
          }*/
        });
      });
    };
    getDataList();
    // 跳转子集列表
    const handleSeriesList = (mediaInfo) => {
      router.push({
        name:
          "mediaslistserieslist" +
          (queryList.mediatype != "" ? queryList.mediatype : "all"),
        query: {
          mediaid: mediaInfo.mediaid,
          groupid: mediaInfo.groupid,
          mediatype: mediaInfo.mediatype,
        },
      });
    };
    // 添加
    const handleCreate = () => {
      router.push({
        name:
          "mediaslistcreatemedia" +
          (queryList.mediatype != "" ? queryList.mediatype : "all"),
        query: {
          groupid: queryList.groupid == "" ? 0 : queryList.groupid,
          mediatype: queryList.mediatype,
        },
      });
    };

    // 媒资编辑
    const handleEdit = (row) => {
      if (row.mediatype == "liveroom") {
        const localQuery = {
          mediaid: row.mediaid,
          groupid: row.groupid,
          mediatype: row.mediatype,
          isedit: 1,
        };
        switch (router.currentRoute.value.name) {
          case "mediaslistall":
            router.push({ path: "/medias/list/all/detail", query: localQuery });
            break;
          case "mediaslistliveroom":
            router.push({
              path: "/medias/list/liveroom/detail",
              query: localQuery,
            });
            break;
          default:
            router.push({ path: "/media/detail/index", query: localQuery });
            break;
        }
      } else {
        let routerPushName = "mediaslisteditmedia";
        let query = {
          mediaid: row.mediaid,
          groupid: row.groupid,
          mediatype: row.mediatype,
        };
        if (queryList.mediatype != "") {
          routerPushName += queryList.mediatype;
        } else {
          query["isall"] = 1;
          routerPushName += "all";
        }
        router.push({ name: routerPushName, query: query });
      }
    };

    //媒资审核
    const handleReview = (row) => {
      ElMessageBox.confirm(
        "确定申请 <strong>" + row.name + "</strong> 进行审核吗？",
        "媒资审核",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          mediasReview({ mediaids: [row.mediaid] }).then((response) => {
            if (response.errcode == 0) {
              ElMessage({
                type: "success",
                message: response.msg,
                duration: 2000,
              });
              getDataList();
            } else {
              console.log(response);
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //媒资上下线
    const handleOnOff = (row) => {
      let mediaOption = "";
      let inputPlace = "";
      if (row.inuse == 1) {
        mediaOption = "下线";
        inputPlace = "请填写下线原因（必填）";
      } else {
        mediaOption = "上线";
        inputPlace = "请填写上线原因（选填）";
      }
      ElMessageBox.prompt(
        "确定 <strong>" +
          row.name +
          "</strong> 进行 <strong>" +
          mediaOption +
          "</strong> 吗？",
        "媒资状态变更",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputValidator: (val) => {
            if (row.inuse == 1 && val === null) {
              return false; //初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
            } else {
              return true;
            }
          },
          inputPlaceholder: inputPlace,
          inputErrorMessage: "请输入下线原因",
        }
      )
        .then((val) => {
          let postInuse = row.inuse == 1 ? 0 : 1;
          mediasOnOff({
            inuse: postInuse,
            mediaids: [row.mediaid],
            comments: val.value,
          }).then((response) => {
            if (response.errcode == 0) {
              ElMessage({
                type: "success",
                message: response.msg,
                duration: 2000,
              });
              getDataList();
            } else {
              console.log(response);
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };
    // 搜索建议
    const handleSearchSuggest = (value, cb) => {
      let suggestQuery = {};
      suggestQuery["corpid"] = store.getters.corpinfo.corpid;
      suggestQuery["groupid"] = groupid;
      suggestQuery["state"] = 1;
      suggestQuery["prefix"] = value;
      const suggestList = ref([]);
      getSearchSuggest(suggestQuery).then((response) => {
        if (response.data.list.length > 0) {
          response.data.list.forEach(function (suginfo) {
            suggestList.value.push({ value: suginfo.name });
          });
          console.log(suggestList.value);
        }
      });
      cb(suggestList.value);
    };
    // 弹窗相关
    const toDialogData = reactive({});
    const dialogTitle = ref("");
    const dialogVisible = ref({
      AndvancedSearch: false,
      OriginalLibrary: false,
      RelPackage: false,
      MediaShare: false,
      LiveRoomReview: false,
    });
    const handleDialog = (dialogName, data) => {
      toDialogData.value = {};
      switch (dialogName) {
        case "AndvancedSearch":
          dialogTitle.value = "高级搜索";
          asyncComponentAndvancedSearch.value = "AndvancedSearch";
          break;
        case "OriginalLibrary":
          dialogTitle.value = "媒资素材库";
          asyncComponentOriginalLibrary.value = "OriginalLibrary";
          break;
        case "RelPackage":
          dialogTitle.value = "选择关联内容包";
          asyncComponentRelPackage.value = "RelPackage";
          toDialogData.mediaids = [data.mediaid];
          toDialogData.packageids = data.packageids;
          relPackageComponentsKey.value = new Date().getTime();
          break;
        case "MediaShare":
          dialogTitle.value = "媒资分享";
          asyncComponentMediaShare.value = "MediaShare";
          toDialogData.medias = [data];
          mediaShareComponentsKey.value = new Date().getTime();
          break;
        case "LiveRoomReview":
          dialogTitle.value = "预览直播间";
          toDialogData.medias = data;
          asyncComponentLiveRoomReview.value = "LiveRoomReview";
          liveRoomReviewComponentKey.value = new Date().getTime();
          break;
      }
      dialogVisible.value[dialogName] = true;
    };
    const cancelDialog = (dialogName) => {
      dialogVisible.value[dialogName] = false;
    };
    // 媒资详情
    const handleMediaDetail = (row) => {
      const detailQuery = {
        mediaid: row.mediaid,
        groupid: row.groupid,
        mediatype: row.mediatype,
      };
      switch (route.path) {
        case "/medias/list/all":
          router.push({ path: "/medias/list/all/detail", query: detailQuery });
          break;
        case "/medialist/index":
          router.push({ path: "/media/detail", query: detailQuery });
          break;
        case "/medias/list/liveroom":
          router.push({
            path: "/medias/list/liveroom/detail",
            query: detailQuery,
          });
          break;
        case "/medias/list/article":
          router.push({
            path: "/medias/list/article/detail",
            query: detailQuery,
          });
          break;
        case "/medias/list/imageset":
          router.push({
            path: "/medias/list/imageset/detail",
            query: detailQuery,
          });
          break;
        case "/medias/list/shortvideo":
          router.push({
            path: "/medias/list/shortvideo/detail",
            query: detailQuery,
          });
          break;
        case "/medias/list/longvideo":
          router.push({
            path: "/medias/list/longvideo/detail",
            query: detailQuery,
          });
          break;
      }
    };

    //复选框
    const batchCheckBoxData = ref([]);
    const batchCheckBoxAllData = ref([]);
    
    const tableHeight = ref();
    const tableref = ref(null);
    const handleSelectionChange = (val) => {
      batchCheckBoxData.value = [];
      batchCheckBoxAllData.value = [];
      if (val.length > 0) {
        val.forEach(function (item) {
          batchCheckBoxData.value.push(item.mediaid);
          batchCheckBoxAllData.value.push(item);
        });
      }
    };
    const handleRowClick = (row) => {
      tableref.value.toggleRowSelection(row);
    };

    onMounted(() => {
      tableHeight.value =
        window.innerHeight - tableref.value.$el.offsetTop - 80;
    //   console.log(
    //     tableref.value,
    //     tableref.value.$el,
    //     window.innerHeight,
    //     tableref.value.$el.offsetTop,
    //     tableHeight.value
    //   );
    });


    //排序
    const handleTableSortChange = (column) => {
      if (column.order == "ascending") {
        queryList.orderby = column.prop;
      } else if (column.order == "descending") {
        queryList.orderby = "-" + column.prop;
      } else {
        queryList.orderby = "";
      }
      getDataList();
    };
    // 批量操作
    const handleBatchCommand = (command) => {
      if (batchCheckBoxData.value.length == 0) {
        ElMessage({
          type: "warning",
          message: "请选择批量操作的数据",
          duration: 2000,
        });
        return;
      }
      //批量关联内容包特殊处理
      if (command == "refpackage") {
        dialogTitle.value = "选择批量关联内容包";
        asyncComponentRelPackage.value = "RelPackage";
        toDialogData.mediaids = batchCheckBoxData.value;
        toDialogData.packageids = [];
        relPackageComponentsKey.value = new Date().getTime();
        dialogVisible.value["RelPackage"] = true;
        return;
      }
      // 批量媒资分享
      if (command == "mediashare") {
        dialogTitle.value = "媒资批量分享";
        asyncComponentMediaShare.value = "MediaShare";
        toDialogData.medias = batchCheckBoxAllData.value;
        dialogVisible.value["MediaShare"] = true;
        mediaShareComponentsKey.value = new Date().getTime();
        return;
      }

      // 其他批量操作处理
      let elMsg = "";
      let inputPlac = "";
      switch (command) {
        case "review":
          elMsg = "批量申请审核";
          break;
        case "online":
          elMsg = "批量上线";
          inputPlac = "请输入批量上线的原因（选填）";
          break;
        case "offline":
          elMsg = "批量下线";
          inputPlac = "请输入批量下线的原因（必填）";
          break;
      }
      // 需要填写提交内容的提示框
      if (command == "online" || command == "offline") {
        ElMessageBox.prompt(
          "确定 <strong>" + elMsg + "</strong> 吗？",
          "批量操作",
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            inputValidator: (val) => {
              if (command == "offline" && val === null) {
                return false; //初始化的值为null，不做处理的话，刚打开MessageBox就会校验出错，影响用户体验
              } else {
                return true;
              }
            },
            inputPlaceholder: inputPlac,
            inputErrorMessage: "请输入下线原因",
          }
        )
          .then((val) => {
            let postInuse = command == "online" ? 1 : 0;
            mediasOnOff({
              inuse: postInuse,
              mediaids: batchCheckBoxData.value,
              comments: val.value,
            }).then((response) => {
              if (response.errcode == 0) {
                ElMessage({
                  type: "success",
                  message: response.msg,
                  duration: 2000,
                });
                getDataList();
              } else {
                console.log(response);
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
        // 仅是确定的提示框
      } else {
        ElMessageBox.confirm(
          "确定 <strong>" + elMsg + "</strong> 吗？",
          "批量操作",
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            if (command == "review") {
              mediasReview({ mediaids: batchCheckBoxData.value }).then(
                (response) => {
                  if (response.errcode == 0) {
                    ElMessage({
                      type: "success",
                      message: response.msg,
                      duration: 2000,
                    });
                    getDataList();
                  } else {
                    console.log(response);
                  }
                }
              );
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }
    };

    const handleLoadImage = (row, e) => {
      console.log(row.thumbs[0].viewurl);
      console.log(e);
    };

    const reloadLists = () => {
      getDataList()
    }
    return {
      relPackageComponentsKey,
      mediaShareComponentsKey,
      liveRoomReviewComponentKey,
      canEditMediaType,
      groupid,
      isloading,
      tableData,
      listGoodsCount,
      queryList,
      groupLists,
      handleGroupChange,
      handleGroupClear,
      mediaTypes,
      handleMediaTypeChange,
      handleMediaTypeClear,
      categoryData,
      handleCategoryChange,
      handleCategoryClear,
      handleKeywordClear,
      srcList,
      getDataList,
      handleSeriesList,
      handleCreate,
      handleEdit,
      handleReview,
      handleOnOff,
      handleSearchSuggest,
      handleMediaDetail,
      asyncComponentAndvancedSearch,
      asyncComponentOriginalLibrary,
      asyncComponentRelPackage,
      asyncComponentMediaShare,
      asyncComponentLiveRoomReview,
      toDialogData,
      dialogTitle,
      dialogVisible,
      handleDialog,
      cancelDialog,
      handleSelectionChange,
      handleRowClick,
      handleTableSortChange,
      tableref,
      tableHeight,
      handleBatchCommand,
      handleLoadImage,
      reloadLists
    };
  },
};
</script>

<style scoped  lang="scss">
</style>
